package com.uatair.common.client;

import com.alibaba.fastjson2.JSONObject;
import com.uatair.common.config.MqttConfig;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

/**
 * @author 14820
 */
@Component
public class PushCallback implements MqttCallback {
    private static final Logger logger = LoggerFactory.getLogger(PushCallback.class);

    @Autowired
    private MqttConfig mqttConfig;

    @Autowired
    private ApplicationContext applicationContext;

    private static MqttClient client;

    private String topic;
    private int qos;
    private String message;

    @Override
    public void connectionLost(Throwable throwable) {
        logger.info("连接断开，可以做重连");
//        if (client.isConnected() || client == null) {
            mqttConfig.getSecondaryMqttPushClient();
            mqttConfig.getPrimaryMqttPushClient();
//        }
    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
//        logger.info("接收消息Qos : {}", mqttMessage.getQos());
//        logger.info("接收消息主题：{}，内容 : {}", topic, new String(mqttMessage.getPayload()));
        this.topic = topic;
        this.qos = mqttMessage.getQos();
        this.message = new String(mqttMessage.getPayload());
        // 发布事件
        applicationContext.publishEvent(
                new MqttMessageEvent(this, topic, mqttMessage.getQos(), new String(mqttMessage.getPayload()))
        );
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        logger.info("deliveryComplete---------{}", iMqttDeliveryToken.isComplete());
    }

    public String receive() {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("topic", topic);
        jsonObject.put("qos", qos);
        jsonObject.put("msg", message);
        return jsonObject.toString();
    }
}
